Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

787
Visualizações
DataAnnotation [Index(IsUnique = true)] on a column throws error Attribute 'Index' is not valid on this declaration type

This is my first time exploring DataAnnotations (I was hoping to use this over fluent)...and I don't understand why the following code throws a compile time error:

CS0592 - Attribute 'Index' is not valid on this declaration type. It is only valid on 'class' declaration

public class Holiday
{
    [Key]
    public int Id { get; set; }

    [Required]
    [Index(IsUnique = true)]
    public DateTime? Date { get; set; }

    public string Name { get; set; }
}

My goal is to make the Date column UNIQUE...and I thought using [Index(IsUnique = true)] on a column is the correct way to make it unique...but it is not allowing me to use the Index attribute on columns, only on classes...

Please teach me how to achieve this? 🙏🙏🙏

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

Well, the Index attribute is the data annotation equivalent of the HasIndex fluent API, and similar to the API, it's meant to be applied at the entity (class) level, providing the properties that make up the index, in order , plus other information such as the index. name, if it is unique, etc.

So in your case you would need something like this

 [Index(nameof(Holiday.Date), IsUnique = true)] public class Holiday { // ... }

which corresponds to the following fluent configuration

 modelBuilder.Entity<Holiday>() .HasIndex(e => e.Date) .IsUnique();

Actually all of this is well explained with examples in the Indexes section of the official EF Core documentation.

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda